export class Task<T> extends Promise<T> {
    // 创建异步任务
    public static create<T>(executor: (
        resolve: (value: T | PromiseLike<T>) => void,
        reject: (reason?: any) => void
    ) => void): Task<T> {
        return new Task((resolve, reject) => {
            // 使用setTimeout确保异步执行
            setTimeout(() => {
                try {
                    executor(resolve, reject);
                } catch (error) {
                    reject(error);
                }
            }, 0);
        });
    }

    // 静态延迟方法
    public static delay(ms: number): Task<void> {
        return Task.create(resolve => setTimeout(resolve, ms));
    }

    // 实例延迟方法
    public delay(ms: number): Task<T> {
        return this.then(value => 
            Task.delay(ms).then(() => value)
        ) as Task<T>;
    }

    // 可取消功能
    private cancelCallback: (() => void) | null = null;
    private isCancelled: boolean = false;
    
    public cancelable(cancelCallback: () => void): Task<T> {
        this.cancelCallback = cancelCallback;
        return this;
    }
    
    public cancel(): void {
        if (!this.isCancelled) {
            this.isCancelled = true;
            if (this.cancelCallback) {
                this.cancelCallback();
                this.cancelCallback = null;
            }
        }
    }

    // 重写then方法，添加取消检查
    then<TResult1 = T, TResult2 = never>(
        onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined,
        onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined
    ): Task<TResult1 | TResult2> {
        return super.then(
            onfulfilled && ((value) => this.isCancelled ? Promise.reject(new Error('Task cancelled')) : onfulfilled(value)),
            onrejected && ((reason) => this.isCancelled ? Promise.reject(new Error('Task cancelled')) : onrejected(reason))
        ) as Task<TResult1 | TResult2>;
    }

    // 重写catch方法
    catch<TResult = never>(
        onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null | undefined
    ): Task<T | TResult> {
        return super.catch(
            onrejected && ((reason) => this.isCancelled ? Promise.reject(new Error('Task cancelled')) : onrejected(reason))
        ) as Task<T | TResult>;
    }

    // 重写finally方法
    finally(onfinally?: (() => void) | null | undefined): Task<T> {
        return super.finally(() => {
            if (this.isCancelled) {
                return Promise.reject(new Error('Task cancelled'));
            }
            return onfinally?.() ?? undefined;
        }) as Task<T>;
    }
}